package com.yoomiito.app.ui.yijiayou

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import com.yoomiito.app.R
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.oilcard.OilCardData
import com.yoomiito.app.model.oilcard.OilCardInfo
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.capture.CaptureActivity
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.dialog.SystemTipDialog
import com.yoomiito.app.widget.dialog.TipDialog
import kotlinx.android.synthetic.main.act_jiayou.*
import kotlinx.android.synthetic.main.title_bar.*


class OilCardActivity : BaseActivity<OilCardPresenter>() {

    companion object {
        const val FirstGetFreeOilCard = "get_free_oil_card"
        fun start(context: Context, firstGetFreeOilCard: String = "") {
            val intent = Intent(context, OilCardActivity::class.java)
            intent.putExtra(Const.Common.Key, firstGetFreeOilCard)
            context.startActivity(intent)
        }
    }

//    private var mLocationClient: AMapLocationClient? = null
    private val oilCardData = OilCardData()
//    private var option: AMapLocationClientOption? = null
    private val versionName = AllUtils.getVersionInfo().versionName
    private val mFreeBuyUrl = "https://mimitao-cdn.aijiamai.com/static/30@3x.png?$versionName"
    private val mPaySuccessUrl = "https://mimitao-cdn.aijiamai.com/static/200@3x.png?$versionName"
    private val mRule1 = "https://mimitao-cdn.aijiamai.com/app/sm_1@3x.png?$versionName"
    private val mRule2 = "https://mimitao-cdn.aijiamai.com/app/sm_2@3x.png?$versionName"
//    private val mLocationListener = AMapLocationListener { p0 ->
//        L.i("定位结果错误信息：${p0?.errorCode}  ${p0?.errorInfo}")
//        L.i("定位结果：lat:${p0?.latitude} lng:${p0?.longitude} \n${p0?.address}")
//
//        dismissLoading()
//        when (p0?.errorCode) {
//            AMapLocation.LOCATION_SUCCESS -> { //
//                val gps1 = GPSConverterUtils.gcj_To_Gps84(p0?.latitude,p0?.longitude)
//                L.i("转换GPS： lat=${gps1.lat} lng=${gps1.lon}")
//                val gps2 = GPSConverterUtils.gcj02_To_Bd09(p0?.latitude,p0?.longitude)
//                L.i("转换BD： lat=${gps2.lat} lng=${gps2.lon}")
//
//                oilCardData.latitude = p0?.latitude //获取纬度信息
//                oilCardData.longitude = p0?.longitude//获取经度信息
////                L.i("坐标系：lat:${gps.lat}   ${gps.lon}")
////                val g = GPSConverterUtils.gcj02_To_Bd09(p0?.latitude, p0?.longitude)
////                L.i("坐标系1：lat:${g.lat}   ${g.lon}")
//                oilCardView.updateData(oilCardData)
//                oilCardView.addOil()
//            }//定位成功
//            else -> "定位失败，请重试".showToast()
//        }
//    }

    override fun getLayoutId(): Int = R.layout.act_jiayou

    override fun newP(): OilCardPresenter = OilCardPresenter(App.mAppConfig)

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        val key = intent.getStringExtra(Const.Common.Key)
        iv_back_left.setOnClickListener { finish() }
        tv_center.text = "优米加油卡"
        tv_right.text = "明细"
        tv_right.visibility = View.VISIBLE
        tv_right.setOnClickListener { OilCardDetailActivity.start(this) }
        tipLl.visibility = View.GONE
        pay.background = ColorUtils.gradientAndRadius("#FFFF6F4B", "#FFFFA54D", 23f)
        pay.setOnClickListener {
            showOilRuleDialog(oilCardData.address)
        }
//        oilCardView.reLocation = {
//            startLocation()
//        }
        startCapture.setOnClickListener { requestCamera() }
        ImageLoader.getInstance().into(this, mRule1, explain1)
        ImageLoader.getInstance().into(this, mRule2, explain2)

        initLocation()
        initRefresh()
        showLoading()
        requestData()
        if (FirstGetFreeOilCard == key) {
            showTipDialog(mFreeBuyUrl)
        }
    }

    private fun initRefresh() {
        refreshLayout.setOnRefreshListener {
            requestData()
        }
    }

    private fun requestData() {
        p.getOilCardInfo()
    }

    override fun onStop() {
//        mLocationClient?.stopLocation()
        super.onStop()
    }

    private fun initLocation() {
//        mLocationClient = AMapLocationClient(applicationContext)
//        mLocationClient?.setLocationListener(mLocationListener)
//        mLocationClient?.setLocationOption(option())
    }

//    private fun option(): AMapLocationClientOption {
//        if (option == null) {
//            option = AMapLocationClientOption()
//            ////LocationMode.Hight_Accuracy：高精度；
//            ////LocationMode. Battery_Saving：低功耗；
//            ////LocationMode. Device_Sensors：仅使用设备；
//            option?.locationMode = AMapLocationClientOption.AMapLocationMode.Battery_Saving
//
//            option?.isOnceLocation = true //单次定位
//            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
//            //如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//            option?.isOnceLocationLatest = true
//            option?.isNeedAddress = true //是否需要返回地址描述。
//            option?.httpTimeOut = 3000 //定位超时时间
//        }
//        return option!!
//    }

    private fun startLocation() {
        val lm = this.getSystemService(LOCATION_SERVICE) as LocationManager
        val open = lm.isProviderEnabled(LocationManager.GPS_PROVIDER)//判断位置信息权限是否打开
        if (open) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                AllUtils.requestPermission3(this, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe { per ->
                            when {
                                per.granted -> {
                                    location()
                                }
                                per.shouldShowRequestPermissionRationale -> {

                                }
                                else -> {
                                    "请去设置中开启定位权限".showToast()
                                }
                            }
                        }
            } else {
                location()
            }
        } else {
            val dialog = TipDialog(this)
            dialog.setCancelText("取消")
            dialog.setSureText("去开启")
            dialog.setContent("请开启位置信息,以便寻找附近油站")
            dialog.setTitle("提示")
            dialog.setClickListener {
                dialog.dismiss()
                val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                context.startActivity(intent)
            }
            dialog.show()
        }
    }

    fun isOPen(context: Context?): Boolean {
        if (context == null) {
            return true
        }
        var locationMode = 0
        val locationProviders: String
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            locationMode = try {
                Settings.Secure.getInt(context.contentResolver, Settings.Secure.LOCATION_MODE)
            } catch (e: Settings.SettingNotFoundException) {
                e.printStackTrace()
                return false
            }
            locationMode != Settings.Secure.LOCATION_MODE_OFF
        } else {
            locationProviders = Settings.Secure.getString(context.contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED)
            !TextUtils.isEmpty(locationProviders)
        }
    }

    private fun location() {
        L.i("开始定位")
        showLoading()
//        mLocationClient?.startLocation()
    }

    private fun requestCamera() {
        AllUtils.requestPermission2(this, Manifest.permission.CAMERA).subscribe { per ->
            when {
                per.granted -> {
                    CaptureActivity.startForResult(this)
                }
                per.shouldShowRequestPermissionRationale -> {

                }
                else -> {
                    "请去设置中开启相机权限".showToast()
                }
            }
        }
    }

    fun setInfo(t: OilCardData?) {
        dismissLoading()
        refreshLayout.isRefreshing = false
        t?.let {
            oilCardData.money = it.money
            oilCardData.nums = it.nums
            oilCardData.totalDiscount = it.totalDiscount
            oilCardData.tips = it.tips
            oilCardData.address = it.address
            tipLl.visibility = View.VISIBLE
            oilCardView.updateData(it)
            tip.text = it.tips
            if (!TextUtils.isEmpty(it.imgUrl))
                ImageLoader.getInstance().into(this, it.imgUrl, explain3)
        }
    }

    fun paySuccess() {
        p.getOilCardInfo()
        showTipDialog(mPaySuccessUrl)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == CaptureActivity.REQUESTCODE && data != null) {
            val result = data.getSerializableExtra(Const.Common.Data) as OilCardInfo
            showDialog(result)
        }
    }

    private fun showDialog(info: OilCardInfo) {
        val tipDialog = TipDialog(this)
        tipDialog.setCancelText("取消")
        tipDialog.setContent("是否确认充值至该账户？")
        tipDialog.setSureText("确定充值")
        tipDialog.setTitle("优米加油卡")
        tipDialog.setTitleVisible(true)
        tipDialog.setClickListener {
            tipDialog.dismiss()
            showLoading()
            p.actCode(info.code)
        }
        tipDialog.show()
    }

    private fun showOilRuleDialog(data: String) {
        if (data.isEmpty()) {
            buyOilCard()
        } else {
            val tipDialog = TipDialog(this)
            tipDialog.setCancelText("取消")
            tipDialog.setContent(data)
            tipDialog.setSureText("确定充值")
            tipDialog.setTitle("加油卡使用范围")
            tipDialog.setTitleVisible(true)
            tipDialog.setClickListener {
                tipDialog.dismiss()
                buyOilCard()
            }
            tipDialog.show()
        }
    }

    private fun buyOilCard() {
        NewGoodsInfoActivity.toGoodsInfo(this, "5230629252506342", Type.ServiceConfigGoodsType.GoodsMainTypePrivateGoods.toString())
    }

    private fun showTipDialog(url: String) {
        val tipDialog = SystemTipDialog(context)
        tipDialog.setAdUrl(url)
        tipDialog.setIvWidthHeight(DensityUtil.dp2px(315f), DensityUtil.dp2px(182f))
        tipDialog.show()
    }

    override fun eventMessage(eventMessage: EventMessage?) {
        super.eventMessage(eventMessage)
        if (Type.EventMsgType.BuyComplete == eventMessage?.eventType && Type.EventMsgType.Success == eventMessage?.code) {
            requestData()
            showTipDialog(mPaySuccessUrl)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
//        mLocationClient?.onDestroy()
    }
}